package com.share.auth.service;

import com.share.common.core.constant.Constants;
import com.share.common.core.constant.SecurityConstants;
import com.share.common.core.domain.R;
import com.share.common.core.exception.ServiceException;
import com.share.common.core.utils.StringUtils;
import com.share.common.core.utils.ip.IpUtils;
import com.share.system.api.model.LoginUser;
import com.share.user.api.RemoteUserInfoService;
import com.share.user.api.domain.UpdateUserLogin;
import com.share.user.api.domain.UserInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import java.util.Date;

/**
 * @author ZhouShuang
 * @version 17
 * @Title
 * @date 2025/10/18 上午10:30
 */
@Component
@RequiredArgsConstructor
public class H5LoginService {

    @Autowired
    private  RemoteUserInfoService remoteUserService;
    private final SysRecordLogService recordLogService;


    /**
     * 登录
     *
     * @param code
     * @return
     */
    public LoginUser login(String code) {
        if (StringUtils.isAnyBlank(code)) {
            throw new ServiceException("微信code必须填写");
        }

        //查询用户信息
        R<UserInfo> userResult = remoteUserService.wxLogin(code);
        System.out.println(userResult.getData());
        System.out.println(userResult.getMsg());
        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
            throw new ServiceException("微信授权登录失败");
        }

        if (R.FAIL == userResult.getCode()) {
            throw new ServiceException(userResult.getMsg());
        }

        //将微信登录的用户信息封装到系统登录用户信息
        UserInfo userInfo = userResult.getData();
        LoginUser loginUser = new LoginUser();
        loginUser.setUserid(userInfo.getId());
        loginUser.setUsername(userInfo.getWxOpenId());
        loginUser.setStatus(userInfo.getStatus());
        if ("2".equals(userInfo.getStatus())) {
            recordLogService.recordLogininfor(userInfo.getWxOpenId(), Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new ServiceException("对不起，您的账号：" + userInfo.getWxOpenId() + "已停用");
        }
        recordLogService.recordLogininfor(userInfo.getWxOpenId(),Constants.LOGIN_SUCCESS,"登录成功");

        //更新登录信息
        UpdateUserLogin updateUserLogin = new UpdateUserLogin();
        updateUserLogin.setUserId(userInfo.getId());
        updateUserLogin.setLastLoginIp(IpUtils.getIpAddr());
        updateUserLogin.setLastLoginTime(new Date());
        remoteUserService.updateUserLogin(updateUserLogin);
        return loginUser;

    }
}
